﻿using System;
using System.Collections.Generic;
using Umbraco.Core;

namespace Com.UmbracoChina.Consult
{
    public class PetaPocoHelper<T>
    {
        /// <summary>
        /// 新增对象
        /// </summary>
        /// <param name="obj">要新增的对象</param>
        public static void Insert(T obj)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            db.Insert(obj);
        }

        /// <summary>
        /// 更新对象
        /// </summary>
        /// <param name="obj">要更新的对象</param>
        public static void Update(T obj)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            db.Update(obj);
        }

        /// <summary>
        /// 删除对象，根据编号
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="sqlStatement">带占位符的sql语句</param>
        public static void DeleteByID(int id, string sqlStatement)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            db.Execute(sqlStatement, id);
        }

        /// <summary>
        /// 根据编号查询
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="sqlStatement">根据编号查询</param>
        /// <returns></returns>
        public static T GetById(int id, string sqlStatement)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            var Data = db.Fetch<T>(sqlStatement, id);
            if (Data.Count > 0)
                return Data[0];
            else
                return default(T);
        }

        /// <summary>
        /// 根据语句查询
        /// </summary>
        /// <param name="sqlStatement">要查询的语句</param>
        /// <returns></returns>
        public static T GetByStatement(string sqlStatement)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            var Data = db.Fetch<T>(sqlStatement);
            if (Data.Count > 0)
                return Data[0];
            else
                return default(T);
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <param name="sqlStatement"></param>
        /// <returns></returns>
        public static IList<T> GetAll(string sqlStatement)
        {
            var db = ApplicationContext.Current.DatabaseContext.Database;
            return db.Fetch<T>(sqlStatement);
        }
    }
}
